#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/uio.h>
#include <string.h>
#include <fcntl.h>


#define HOST "localhost"
#define USERNAME "root"
#define PASSWORD ""
#define DATABASE "tcmu"

struct file_state {
	int fd;
};

void printResult(MYSQL *mysqlPrint);

int main()
{
    struct file_state *state = calloc(1, sizeof(*state));;
    char *path = "/root/shunzi/elvis-test";
    // Open the file with path.(With mode)
	state->fd = open(path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);

    char *buffer_one = "Hello! ";
    char *buffer_two = "World! ";
    struct iovec iv[2];
    iv[0].iov_base = buffer_one;
    iv[0].iov_len = strlen(buffer_one);
    iv[1].iov_base = buffer_two;
    iv[1].iov_len = strlen(buffer_two);
    int ret = writev(state->fd, iv, 2);
    printf("Write result ret is %d.\n", ret);

    MYSQL connection;
    mysql_init(&connection);
    mysql_real_connect(&connection, HOST, USERNAME, PASSWORD, DATABASE, 0, NULL, 0);
    mysql_query(&connection, "set names 'utf8'");
    printf("Start to insert the data to Mysql.\n");
    char *insert_sql_caluse = "REPLACE INTO kv(`Key`, `Value`) VALUES (";
    int i = 0;
    for (i = 0; i < 2; i++)
    {
        char *key = (char *) calloc(5, sizeof(char));
        sprintf(key, "%s%d", "key", i);
        char *sql = (char *) calloc(200, sizeof(char));
        sprintf(sql, "%s'%s', '%s')", insert_sql_caluse, key, (char *) iv[i].iov_base);
        mysql_query(&connection, sql);
        printf("Insert sql is %s\n", sql);
    }		

    mysql_query(&connection, "select * from kv");
    printf("Select Result : \n");
    printResult(&connection);
    mysql_close(&connection);

    struct iovec read_file_iv[2];
    int read_ret = readv(state->fd, read_file_iv, 2);
    printf("Read result ret is %d.\n", read_ret);
    printf("Read result iov[0] is %s.\n", read_file_iv[0].iov_base);
    printf("Read result iov[1] is %s.\n", read_file_iv[1].iov_base);
    return 0;
}

void printResult(MYSQL *mysqlPrint)
{
    MYSQL_RES * result;
    int numFields = 0;
    int numRows = 0;
    MYSQL_FIELD * field;
    MYSQL_ROW row;
    int i = 0;
    result = mysql_store_result(mysqlPrint);
    numFields = mysql_num_fields(result);
    numRows = mysql_num_rows(result);
    while(field = mysql_fetch_field(result))
        printf("%s\t", field->name);
    printf("\n");
    if(result)
    {
        while(row = mysql_fetch_row(result))
        {
            for(i = 0; i < numFields; i++)
            {
                printf("%s\t", row[i]);
            }
            printf("\n");
        }
    }
    mysql_free_result(result);
}
